<template>
  <el-card>
    <div slot="header">
      <el-row type="flex" justify="space-between">
        <h3>商品负责人-编辑</h3>
        <el-row type="flex">
          <el-button size="mini" @click="handleGoBack">返回</el-button>
          <el-button
            type="primary"
            size="mini"
            :loading="btnLoading.submit"
            @click="handleComplete"
          >完成</el-button>
        </el-row>
      </el-row>
    </div>
    <div class="edit-body">
      <el-row>
        <div class="block-header">
          <h4>选择员工</h4>
        </div>
        <ChooseStaff
          ref="staffRef"
          :dataList="chooseStaff.list"
          @updateStaffInfo="updateStaffInfo"
        />
      </el-row>
      <el-row class="center-wrap">
        <div class="block-header">
          <div class="block-header-left">
            <h4>选择品牌/品类</h4>
            <el-radio-group v-model="radioVal" class="radio-group-wrap" @change="handleRadioChange">
              <el-radio
                v-for=" item in radioOptions"
                :key="item.label"
                :label="item.label"
              >{{ item.name }}</el-radio>
            </el-radio-group>
            <el-checkbox
              v-show="!isBrand"
              v-model="checkedAll"
              :disabled="checkedAllDisabled"
              @change="handleChangeCheckAll"
            >全部</el-checkbox>
          </div>
        </div>
        <transfer-select
          ref="transferRef"
          :leftTitle="transfer.config.leftTitle"
          :rightTitle="transfer.config.rightTitle"
          :sourceProps="transfer.config.sourceProps"
          :transferType="radioVal"
          :dataList="transfer.list"
          @getSearchVal="updateBrandList"
          @updateCheckedAll="updateCheckedAll"
        >
          <template v-if="!isBrand" slot="box-header">
            <span>品类等级：</span>
            <el-select v-if="isCateTransfer" v-model="categorySelect.level" placeholder="请选择" @change="handleSelectChange">
              <el-option
                v-for="item in categorySelect.options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-select v-if="isMetal" v-model="metalSelect.level" placeholder="请选择" @change="handleSelectChange">
              <el-option
                v-for="item in metalSelect.options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </template>
          <el-button
            type="primary"
            slot="right-footer"
            @click="handleBuildRelation"
          >建立关系</el-button>
        </transfer-select>
      </el-row>
      <el-row class="right-wrap">
        <div class="block-header">
          <h4>商品负责人与品类/品牌关系</h4>
          <DeleteIcon :disabled="relateList.length == 0" @delete="handleResetRelate" />
        </div>
        <RelateList :dataList.sync="relateList" @delete="deleteRelateList" />
      </el-row>
    </div>
  </el-card>
</template>
<script>
import ChooseStaff from './components/ChooseStaff';
import TransferSelect from './components/TransferSelect';
import RelateList from './components/RelateList';
import DeleteIcon from './components/DeleteIcon';
import {
  CategoryProps,
  BrandProps,
  CATE_LEVEL_OPTIONS,
  CATE_LEVEL_VALUES,
  TRANSFER_TYPE_VALUES
} from './constants';
import { getArraysByMaps } from '@/utils/getUtils';
import {
  getPersonListService,
  getBrandListService,
  getCategoryListService,
  addPersonsService,
  getPersonDetailService
} from '@/api/commodity/departmentManage/departmentManage';
export default {
  components: {
    ChooseStaff,
    TransferSelect,
    RelateList,
    DeleteIcon
  },
  data () {
    return {
      radioVal: TRANSFER_TYPE_VALUES.Category,
      chooseStaff: {
        info: null,
        list: []
      },
      transferConfig: {},
      transfer: {
        config: {},
        list: []
      },
      relateMaps: new Map(),
      relateList: [],
      hrDepartmentId: '',
      categorySelect: {
        level: CATE_LEVEL_VALUES.One,
        forgetList: [],
        options: CATE_LEVEL_OPTIONS
      },
      metalSelect: {
        level: CATE_LEVEL_VALUES.One,
        forgetList: [],
        options: CATE_LEVEL_OPTIONS
      },
      checkedAll: false,
      btnLoading: {
        submit: false
      },
      radioOptions: [
        { label: TRANSFER_TYPE_VALUES.Category, name: '品类' },
        { label: TRANSFER_TYPE_VALUES.Brand, name: '品牌' },
        { label: TRANSFER_TYPE_VALUES.MetalCategory, name: '金属品类' }
      ]
    }
  },
  mounted () {
    const {
      hrDepartmentId,
      authMetalStatus // 已授权品类 金属：1 非金属：3 金属 + 非金属 ：2
    } = this.$route.query
    this.hrDepartmentId = hrDepartmentId
    this.initRadilValAndOptions(authMetalStatus)
    this.setTransferConfigs()
    this.getPersonList()
    this.getPersonDetails()
  },
  computed: {
    isCateTransfer () {
      return this.radioVal == TRANSFER_TYPE_VALUES.Category
    },
    isMetal () {
      return this.radioVal == TRANSFER_TYPE_VALUES.MetalCategory
    },
    isBrand () {
      return this.radioVal == TRANSFER_TYPE_VALUES.Brand
    },
    checkedAllDisabled () {
      return !this.chooseStaff.info
    }
  },
  methods: {
    // 根据已授权品类初始化品牌品类
    initRadilValAndOptions (authMetalStatus) {
      // 金属品类
      if (authMetalStatus == 1) {
        this.radioOptions.shift()
        this.radioVal = TRANSFER_TYPE_VALUES.MetalCategory
      }
      // 非金属品类
      if (authMetalStatus == 3) {
        this.radioOptions.pop()
        this.radioVal = TRANSFER_TYPE_VALUES.Category
      }
    },
    // 设置Transfer组件配置项
    setTransferConfigs () {
      const ConfigMaps = {
        [TRANSFER_TYPE_VALUES.Brand]: BrandProps,
        [TRANSFER_TYPE_VALUES.Category]: CategoryProps,
        [TRANSFER_TYPE_VALUES.MetalCategory]: CategoryProps,
      }
      this.transfer.config = ConfigMaps[this.radioVal] ?? {}
      this.radioVal == TRANSFER_TYPE_VALUES.Brand
        ? this.transfer.list = []
        : this.updateCategoryList()
    },
    // 更新员工信息
    updateStaffInfo (info) {
      this.$refs.transferRef.resetAll()
      this.checkedAll = false
      this.chooseStaff.info = info
    },
    // 更新品牌列表
    updateBrandList (val) {
      this.getBrandList(val)
    },
    // 更新分类列表
    updateCategoryList () {
      let Level = this.isCateTransfer ? this.categorySelect.level : this.metalSelect.level
      if (Level == 0) {
        return this.transfer.list = []
      }
      if (Level == CATE_LEVEL_VALUES.Forget) {
        return this.transfer.list = this.isCateTransfer ? this.categorySelect.forgetList : this.metalSelect.forgetList
      }
      this.getCategoryList(Level)
    },
    // 更新关联集合
    updateRelateList (list, isAll) {
      const { jobNumber } = this.chooseStaff.info ?? {}
      const executeList = list ?? this.relateList
      executeList.forEach(item => {
        const mapKey = this.getRelateMapKey(item)
        if (isAll && item.jobNumber == jobNumber) { // 勾选全部操作 - 删除当前勾选员工所有数据
          this.relateMaps.delete(mapKey)
        }
        if (isAll == undefined) { // 正常勾选操作 - 设置当前建立关系项
          this.relateMaps.set(mapKey, this.getFormatRelateItem(item))
        }
      })
      isAll ? this.relateMaps.set(jobNumber, this.getFormatRelateItem()) : this.relateMaps.delete(jobNumber) // 处理建立关系集合里的全部项
      this.relateList = getArraysByMaps(this.relateMaps)
    },
    // 更新全部checkbox勾选状态
    updateCheckedAll () {
      this.checkedAll = false
    },
    // 删除关系结果集合
    deleteRelateList (item) {
      if (item.mappingName == '全部' && item.jobNumber == this.chooseStaff?.info?.jobNumber) {
        this.checkedAll = false
      }
      const mapKey = this.getRelateMapKey(item)
      this.relateMaps.delete(mapKey)
    },
    // 获取关系Map集合的key
    getRelateMapKey (item) {
      const key = item.mappingId ? `${item.mappingId}-${item.jobNumber}-${item.type}-${item.isMetal}` : item.jobNumber
      return key
    },
    // 获取员工列表
    async getPersonList () {
      const data = { hrDepartmentId: this.hrDepartmentId }
      const res = await getPersonListService(data, '.staff_wrap')
      this.chooseStaff.list = res?.retData ? res.retData : []
    },
    // 获取品牌列表
    async getBrandList (name) {
      const data = {
        brandName: name,
        pageNum: 1,
      }
      const res = await getBrandListService(data, '.left-list-wrap')
      this.transfer.list = res?.retData?.results ? res.retData.results : []
    },
    // 获取分类列表
    async getCategoryList (level = 1) {
      const data = {
        hrDepartmentId: this.hrDepartmentId,
        level,
      }
      const res = await getCategoryListService(data, '.left-list-wrap')
      if (res?.retData) {
        const { nonMetalCategories = [], metalCategories = [] } = res.retData
        if (this.isCateTransfer) {
          this.transfer.list = nonMetalCategories
        }
        if (this.isMetal) {
          this.transfer.list = metalCategories
        }
      }
    },
    // 获取已建立商品负责人详情
    async getPersonDetails () {
      const data = { hrDepartmentId: this.hrDepartmentId }
      const res = await getPersonDetailService(data, '.show-list-wrap')
      if (res?.retData) {
        this.updateRelateList(res.retData)
      }
    },
    // 获取关系列表格式化项
    getFormatRelateItem (item = {}) {
      const isAllChecked = Object.keys(item).length == 0
      const KeyMaps = {
        [TRANSFER_TYPE_VALUES.Brand]: 'brandName',
        [TRANSFER_TYPE_VALUES.Category]: 'categoryName',
        [TRANSFER_TYPE_VALUES.MetalCategory]: 'categoryName',
      }
      const mappingName = item.mappingName ?? item[KeyMaps[this.radioVal]]
      const hasCateNo = item.categoryNo && mappingName.search(item.categoryNo) == -1
      const relateName = hasCateNo ? `${item.categoryNo} ${mappingName}` : mappingName
      const radioType = this.radioVal == TRANSFER_TYPE_VALUES.Brand ? TRANSFER_TYPE_VALUES.Brand : TRANSFER_TYPE_VALUES.Category
      const relateItem = {
        ...item,
        ...this.chooseStaff.info,
        type: item.type ?? radioType,
        mappingId: item.mappingId ?? (isAllChecked ? 0 : item.uuid),
        mappingName: isAllChecked ? '全部' : relateName
      }
      return relateItem
    },
    // 下拉change
    handleSelectChange () {
      this.updateCategoryList()
    },
    // 建立关系
    handleBuildRelation () {
      const hasNoSelectStaff = !this.chooseStaff.info
      const selectedTransferList = [...this.$refs.transferRef.selectedList]
      const hasNoSelectTransfer = selectedTransferList.length == 0
      if (hasNoSelectStaff || hasNoSelectTransfer) {
        return this.$message.warning('请选择员工或品牌/品类信息后再进行关系建立！')
      }
      const relateList = selectedTransferList.map(item => ({ ...this.getFormatRelateItem(item) }))
      this.updateRelateList(relateList)
    },
    // 完成
    handleComplete () {
      const hasNoRelateList = this.relateList.length === 0
      if (hasNoRelateList) return this.$message.warning('请建立关系后再进行提交！')
      const pickKeys = ['hrDepartmentId', 'jobNumber', 'userName', 'mappingId', 'mappingName', 'type', 'isMetal']
      const ownerList = this.relateList.map(item => ({
        ..._.pick(item, pickKeys),
        categoryLevel: item.levelNum ?? CATE_LEVEL_VALUES.One
      }))
      const data = {
        data: ownerList,
        hrDepartmentId: this.hrDepartmentId
      }
      this.submitOwnerInfo(data)
    },
    // 品类/品牌切换
    handleRadioChange () {
      if (this.radioVal == TRANSFER_TYPE_VALUES.Category) {
        this.categorySelect.level = CATE_LEVEL_VALUES.One
      }
      if (this.radioVal == TRANSFER_TYPE_VALUES.MetalCategory) {
        this.metalSelect.level = CATE_LEVEL_VALUES.One
      }
      if (this.radioVal == TRANSFER_TYPE_VALUES.Brand) {
        this.checkedAll = false
      }
      this.setTransferConfigs()
    },
    // 选择全部
    handleChangeCheckAll (state) {
      this.$refs.transferRef.resetAll()
      this.updateRelateList(null, state)
    },
    // 重置关联结果集合数据
    handleResetRelate () {
      this.$confirm('确定后将清空所有已建立关系结果集合，您确认吗？', '清空', {
        type: 'warning',
      }).then(() => {
        this.relateList = []
        this.relateMaps = new Map()
        this.$refs.staffRef.resetState()
      }).catch(() => {});
    },
    // 返回列表页
    handleGoBack () {
      this.$router.push({ name: 'departmentManageHome' })
    },
    // 提交商品负责人信息
    async submitOwnerInfo (data) {
      const loadingFn = state => { this.btnLoading.submit = state }
      const res = await addPersonsService(data, loadingFn)
      if (res.code != '0') return
      const { nonMetalCategories = [], metalCategories = [] } = res.data
      const nonMetalLen = nonMetalCategories.length
      const metalLen = metalCategories.length
      if (!nonMetalLen && !metalLen) {
        this.handleGoBack()
        return this.$message.success('提交成功')
      }
      if (metalLen) {
        this.radioVal = TRANSFER_TYPE_VALUES.MetalCategory
        this.metalSelect.level = CATE_LEVEL_VALUES.Forget
        this.transfer.list = this.metalSelect.forgetList = metalCategories
      }
      if (nonMetalLen) {
        this.radioVal = TRANSFER_TYPE_VALUES.Category
        this.categorySelect.level = CATE_LEVEL_VALUES.Forget
        this.transfer.list = this.categorySelect.forgetList = nonMetalCategories
      }
      this.setTransferConfigs()
      this.$message.warning('有品类遗漏勾选，请完善后再提交')
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .el-select {
  width: 70%;
}
.edit-body {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.radio-group-wrap {
  margin: 0 20px;
}
.center-wrap {
  margin: 0 10px;
}
.right-wrap {
  flex: 1;
}
.block-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 10px;
  border: 1px solid #EBEEF5;
  background-color: #FFF;
  border-radius: 4px;
  .block-header-left {
    display: flex;
    align-items: baseline;
  }
}
</style>
